<?php

class IndexAction extends AdminbaseAction {

    protected $cache_model;

    function _initialize() {
        parent::_initialize();
    }
	
    public function banji() {
		
		$banji=M('banji');
		$this->dao = $banji;
		$count = $this->dao->count();
		if ($count) {
			import("@.ORG.Page");
			$listRows = 15;
			$page = new Page($count, $listRows);
			$pages = $page->show();
			$list = $this->dao->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
			foreach($list as $k=>$v){
				$yuansuo=M('category')->find($v['yuan_id']);
				$list[$k]['yuansuo']=$yuansuo['catname'];
			}
			$this->assign('pages', $pages);
			$this->assign('list', $list);
		}
		
		$addyuansuo=M('category')->where("parentid=31")->select();
		$this->assign('addyuansuo', $addyuansuo);
        $this->display();
    }

    public function banjiadddo() {
		
		if($_POST['addtitle']=='' || $_POST['addyuansuo']==''){
            $this->error("请填写班级名称和所属园所");
		}else{
			$add['title']=$_POST['addtitle'];
			$add['yuan_id']=$_POST['addyuansuo'];
			if(M('banji')->add($add)){
				$this->success("添加成功");
			}else{
				$this->error("添加失败");
			}
		}
    }
    public function banjieditdos() {
		if($_POST['edittitle']=='' || $_POST['edityuansuo']==''){
            $this->error("请填写班级名称和所属园所");
		}else{
			$add['id']=$_POST['editid'];
			$add['title']=$_POST['edittitle'];
			$add['yuan_id']=$_POST['edityuansuo'];
			if(M('banji')->save($add)){
				$this->success("修改成功");
			}else{
				$this->error("修改失败");
			}
		}
    }
    public function banjieditdoajax() {
		$id=$_POST['id'];
		$banji=M('banji')->find($id);
		$yuansuo=M('category')->find($banji['yuan_id']);
		$banji['yuansuo']=$yuansuo['catname'];
		$banjioption="<option value='".$banji['yuan_id']."'>".$banji['yuansuo']."</option>";
		$allyuansuo=M('category')->where("parentid=31 and id!=".$banji['yuan_id']."")->select();
		foreach($allyuansuo as $k=>$v){
			$banjioption.="<option value='".$v['id']."'>".$v['catname']."</option>";
		}
		$banji['banjioption']=$banjioption;
		echo json_encode($banji);
		exit;
    }
    public function delbanjiajax() {
		$id=$_POST['id'];
		$banji=M('banji')->where("id=".$id."")->delete();
		if($banji){
			$tishi="删除成功";
		}else{
			$tishi="删除失败";
		}
		echo $tishi;
		exit;
    }

    public function jiaoshi() {
		
		$jiaoshi=M('jiaoshi');
		$this->dao = $jiaoshi;
		$count = $this->dao->count();
		if ($count) {
			import("@.ORG.Page");
			$listRows = 15;
			$page = new Page($count, $listRows);
			$pages = $page->show();
			$list = $this->dao->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
			foreach($list as $k=>$v){
				$yuansuo=M('category')->find($v['yuan_id']);
				$list[$k]['yuansuo']=$yuansuo['catname'];
				$banji=M('banji')->find($v['ban_id']);
				$list[$k]['banji']=$banji['title'];
			}
			$this->assign('pages', $pages);
			$this->assign('list', $list);
		}
		
		$addyuansuo=M('category')->where("parentid=31")->select();
		$this->assign('addyuansuo', $addyuansuo);
		$addbanji=M('banji')->where("yuan_id=".$addyuansuo[0]['id']."")->select();
		$this->assign('addbanji', $addbanji);
        $this->display();
    }
    public function show_addbanji() {
		$yuan_id=$_POST['yuan_id'];
		$banji=M('banji')->where("yuan_id=".$yuan_id."")->select();
		foreach($banji as $k=>$v){
			$banjioption.="<option value='".$v['id']."'>".$v['title']."</option>";
		}
		echo $banjioption;
		exit;
    }

    public function jiaoshiadddo() {
		
		if($_POST['addtitle']=='' || $_POST['addyuansuo']=='' || $_POST['addbanji']==''){
            $this->error("请填写教师姓名并选择所属园所和所属班级");
		}else{
			$add['title']=$_POST['addtitle'];
			$add['yuan_id']=$_POST['addyuansuo'];
			$add['ban_id']=$_POST['addbanji'];
			if(M('jiaoshi')->add($add)){
				$this->success("添加成功");
			}else{
				$this->error("添加失败");
			}
		}
    }
    public function deljiaoshijax() {
		$id=$_POST['id'];
		$jiaoshi=M('jiaoshi')->where("id=".$id."")->delete();
		if($jiaoshi){
			$tishi="删除成功";
		}else{
			$tishi="删除失败";
		}
		echo $tishi;
		exit;
    }

    public function index() {
        $role = F("Role");
        $this->assign('usergroup', $role[$_SESSION['groupid']]['name']);

        foreach ((array) $_SESSION['_ACCESS_LIST']['ADMIN'] as $key => $r) {
            $modules[] = ucwords(strtolower($key));
        }
        $modules = implode("','", $modules);
        $alltopnode = M('Node')->field('groupid')->where("name in('$modules') and level=2")->group('groupid')->select();
        foreach ((array) $alltopnode as $key => $r) {
            $GroupAccessids[] = $r['groupid'];
        }

        foreach ($this->menudata as $key => $module) {
            if ($module['parentid'] != 0 || $module['status'] == 0)
                continue;
            if (in_array($key, $GroupAccessids) || $_SESSION[C('ADMIN_AUTH_KEY')]) {
                if (empty($module['action']))
                    $module['action'] = 'index';
                $nav[$key] = $module;
                if ($isnav) {
                    $array = array('menuid' => $nav[$key]['parentid']);
                    cookie('menuid', $nav[$key]['parentid']);
                    //$_SESSION['menuid'] = $nav[$key]['parentid'];
                } else {
                    $array = array('menuid' => $nav[$key]['id']);
                }
                if (empty($menuid) && empty($isnav))
                    $array = array();
                $c = array();
                parse_str($nav[$key]['data'], $c);
                $nav[$key]['data'] = $c + $array;
            }
        }
        $this->assign('menuGroupList', $nav);
        $this->assign($this->Config);
        foreach ($nav as $key => $r) {
            $menu[$r['id']] = $this->getnav($r['id']);
        }
        $this->assign('menu', $menu);
        $this->display();
    }
    public function daochudcjieguo() {
//		$dcjieguo=M('dcjieguo')->select();
//		$dcjieguoshu=M('dcjieguo')->count();
//		foreach($dcjieguo as $k=>$v){
//			$dcjieguo[$k]['createtime']=date('Y-m-d H:i:s',$v['createtime']);
//			$dcjieguo['erji'.$k.'']=M('dcdaan')->where("dcjieguo_id=".$v['id']."")->select();
//			$dcjieguoerjishu[$k]=M('dcdaan')->where("dcjieguo_id=".$v['id']."")->count();
//			
//		}
//		$xx=$dcjieguoshu;
//		$yy=$dcjieguoerjishu;
		
		ob_clean();	
		$stadata=M('dcjieguo')->select();
		$dcjieguoshu=M('dcjieguo')->count();
		foreach($stadata as $k=>$v){
			$stadata[$k]['createtime']=date('Y-m-d H:i:s',$v['createtime']);
			$stadata[$k]['erji']=M('dcdaan')->where("dcjieguo_id=".$v['id']."")->select();
			$stadataerjishu[$k]=M('dcdaan')->where("dcjieguo_id=".$v['id']."")->count();
			
		}
		$xx=$stadatashu;
		$yy=$stadataerjishu;
		$stanum   = count($stadata);
		
		//$wangzhi='http://'.$_SERVER['SERVER_NAME'];
		//var_dump($wangzhi);exit;
		include_once('./Joyeasy/Lib/Action/Admin/PHPExcel.php'); 
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
									 ->setLastModifiedBy("Maarten Balliauw")
									 ->setTitle("Office 2007 XLSX Test Document")
									 ->setSubject("Office 2007 XLSX Test Document")
									 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Test result file");
		// Add some data
		$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', '问卷标题')
					->setCellValue('B1', '第一部分标题')
					->setCellValue('C1', '第一部分不满意原因及建议')
					->setCellValue('D1', '第二部分标题')
					->setCellValue('E1', '第二部分不满意原因及建议')
					->setCellValue('F1', '其他建议')
					->setCellValue('G1', '各题题目')
					->setCellValue('H1', '各题答案')
					->setCellValue('I1', '提交时间');
		// Miscellaneous glyphs, UTF-8
		for($i=0; $i<$stanum; $i++) {
			$bb=2;
			$j = $i+$cc+$bb;
			for($ii=0;$ii<$yy[$i];$ii++){
			$objPHPExcel->setActiveSheetIndex(0)
						->setCellValue('A'.$j, $stadata[$i]['title'])
						->setCellValue('B'.$j, $stadata[$i]['yidabiaoti'])
						->setCellValue('C'.$j, $stadata[$i]['yidayuanyin'])
						->setCellValue('D'.$j, $stadata[$i]['erdabiaoti'])
						->setCellValue('E'.$j, $stadata[$i]['erdayuanyin'])
						->setCellValue('F'.$j, $stadata[$i]['qita'])
						
						->setCellValue('G'.($j+$ii), $stadata[$i]['erji'][$ii]['title'])
						->setCellValue('H'.($j+$ii), $stadata[$i]['erji'][$ii]['daan'])
						
						->setCellValue('I'.$j, $stadata[$i]['createtime']);
			}
			$cc=$cc+$ii;
		}
		// Rename worksheet
		$objPHPExcel->getActiveSheet()->setTitle('Simple');
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
		//$user = iconv('utf-8','gb2312',$user);
		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel;charset=utf-8');
		header('Content-Disposition: attachment;filename=dcjieguo'.date('YmdHis',time()).'.xls');
		header('Cache-Control: max-age=0');

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
    }

    public function cache() {
        dir_delete(RUNTIME_PATH . 'Html/');
        dir_delete(RUNTIME_PATH . 'Cache/');
        if (is_file(RUNTIME_PATH . '~runtime.php'))
            @unlink(RUNTIME_PATH . '~runtime.php');
        if (is_file(RUNTIME_PATH . '~allinone.php'))
            @unlink(RUNTIME_PATH . '~allinone.php');
        R('Admin/Category/repair');
        R('Admin/Category/repair');

        foreach ($this->cache_model as $r) {
            savecache($r);
        }
        $forward = $_GET['forward'] ? $_GET['forward'] : U('Index/main');
        $this->assign('jumpUrl', $forward);
        $this->success(L('do_success'));
    }

    public function main() {

        $db = D('');
        $db = DB::getInstance();
        $tables = $db->getTables();

        $info = array(
            'license' => '<b id="Joyeasy_license"></b><b id="Joyeasy_sn"></b>',
            'JOYEASY_VERSION' => VERSION . ' ' . UPDATETIME . ' [ <a href="javascript:;" >' . L('view_new_VERSION') . '</a> ]',
            'SERVER_SOFTWARE' => PHP_OS . ' ' . $_SERVER["SERVER_SOFTWARE"],
            'mysql_get_server_info' => php_sapi_name(),
            'MYSQL_VERSION' => mysql_get_server_info(),
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'max_execution_time' => ini_get('max_execution_time') . L('miao'),
            'disk_free_space' => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
        );
        $this->assign('server_info', $info);
        foreach ((array) $this->module as $rw) {
            if ($rw['type'] == 1) {
                $molule = M($rw['name']);
                $rw['counts'] = $molule->count();
                ;
                $mdata['moduledata'][] = $rw;
            }
        }

        $molule = M('User');
        $counts = $molule->count();
        $userinfos = $molule->find($_SESSION['adminid']);
        $mdata['moduledata'][] = array('title' => L('user_counts'), 'counts' => $counts);

        $molule = M('Category');
        $counts = $molule->count();
        $mdata['moduledata'][] = array('title' => L('Category_counts'), 'counts' => $counts);
        $this->assign($mdata);
        $role = F('Role');

        $userinfo = array(
            'username' => $userinfos['username'],
            'groupname' => $role[$userinfos['groupid']]['name'],
            'logintime' => toDate($userinfos['last_logintime']),
            'last_ip' => $userinfos['last_ip'],
            'login_count' => $userinfos['login_count'] . L('ci'),
        );
        $this->assign('userinfo', $userinfo);

        $this->display();
    }

    // 更换密码
    public function password() {
        if ($_POST['dosubmit']) {
            if (md5($_POST['verify']) != $_SESSION['verify']) {
                $this->error(L('error_verify'));
            }
            if ($_POST['password'] != $_POST['repassword']) {
                $this->error(L('password_repassword'));
            }
            $map = array();
            $map['password'] = sysmd5($_POST['oldpassword']);
            if (isset($_POST['username'])) {
                $map['username'] = $_POST['username'];
            } elseif (isset($_SESSION['adminid'])) {
                $map['id'] = $_SESSION['adminid'];
            }
            //检查用户
            $User = M("user");
            if (!$User->where($map)->field('id')->find()) {
                $this->error(L('error_oldpassword'));
            } else {
                $User->updatetime = time();
                $User->password = sysmd5($_POST['password']);
                $User->save();
                $this->success(L('do_success'));
            }
        } else {
            $this->display();
        }
    }

    // 修改资料
    public function profile() {
        if ($_REQUEST['dosubmit']) {
            $User = M("User");
            if (!$User->create()) {
                $this->error($User->getError());
            }
            $User->update_time = time();
            $User->last_ip = get_client_ip();
            $result = $User->save();
            if (false !== $result) {
                $this->success(L('do_success'));
            } else {
                $this->error(L('do_error'));
            }
        } else {
            $User = M("user");
            $vo = $User->getById($_SESSION['adminid']);
            $this->assign('vo', $vo);
            $this->display();
        }
    }

}

?>